package ua.tyran53red.contacts.channel;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ChannelImp {
	public HashMap<Integer, ChannelObject> readXML() {
		HashMap<Integer, ChannelObject> map = new HashMap<Integer, ChannelObject>();
		try {
			File file = new File("data/contacts_data/channel_list/channel_list_test.xml");
			int counter = 0;
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();
			Document document = documentBuilder.parse(file);
			NodeList nodeList = document.getElementsByTagName("channel");
			for (int s = 0; s < nodeList.getLength(); s++) {
				Node node = nodeList.item(s);
				Element channelElement = (Element) node;
				NodeList nameNodeList = channelElement.getElementsByTagName("name");
				Element nameElement = (Element)nameNodeList.item(0);
				NodeList valueNameNodeList = nameElement.getChildNodes();
				NodeList usersList = channelElement.getElementsByTagName("users");
				Node userNodeList = usersList.item(0);
				Element userElementList = (Element)userNodeList;
				NodeList userElementListNode = userElementList.getElementsByTagName("user");
				HashMap<Integer, String> userList = new HashMap<Integer, String> ();
				for (int i = 0; i < userElementListNode.getLength(); i++) {
					Element userElem = (Element)userElementListNode.item(i);
					NodeList valueUser = userElem.getChildNodes();
					userList.put(i, ((Node)valueUser.item(0)).getNodeValue());
				}
				map.put(counter++,
						new ChannelObject(((Node) valueNameNodeList.item(0))
								.getNodeValue(), userList));
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}
}
